import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:industry_net/base/component/dialog/bottom.dart';
import 'package:industry_net/base/dioUtil/http_man.dart';
import 'package:industry_net/base/dioUtil/net_api.dart';

class UploadMan {
  Future<void> picker(
      {int max = 1, required Function(List<String>) result}) async {
    showActionSheet(
      titles: ['相机', '相册', '取消'],
      onTap: (index) async {
        if (index < 2) {
          if (max == 1 || index == 0) {
            var file = await ImagePicker().pickImage(
                source: index == 0 ? ImageSource.camera : ImageSource.gallery,
                maxHeight: 667,
                maxWidth: 375,
                imageQuality: 50);
            var _url = await _upload(file);
            if (_url.isNotEmpty) {
              result([_url]);
            }
          } else {
            var _files = await ImagePicker().pickMultiImage(
                maxHeight: 667, maxWidth: 375, imageQuality: 50);
            if (_files == null) {
              return;
            }
            List<String> _urls = [];
            for (var item in _files) {
              var _url = await _upload(item);
              if (_url.isNotEmpty) {
                _urls.add(_url);
              }
            }
            result(_urls);
          }
        }
      },
    );
  }

  Future<String> _upload(XFile? file) async {
    var _data = await file?.readAsBytes();
    if (_data != null) {
      var _multipartFile = MultipartFile.fromBytes(_data);
      EasyLoading.show();
      await Future.delayed(Duration(seconds: 3));
      EasyLoading.dismiss();
      return '111';

      var res = await HttpMan().upload(
        Api.uploadImage,
        data: FormData.fromMap({
          "file": _multipartFile,
        }),
      );
      return res.data['url'];
    }
    return '';
  }
}
